package edu.hubu.netdisk.controller;

import edu.hubu.netdisk.entity.MyFile;
import edu.hubu.netdisk.utils.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @author waxijiang
 */
@Controller
@RequestMapping("/files")
@CrossOrigin
public class FileController {

    @Value("${fileLocation}")
    String parentPath;

    Logger logger = LoggerFactory.getLogger(FileController.class);

    @GetMapping("hello")
    @ResponseBody
    public String hello() {
        return parentPath;
    }

    @ResponseBody
    @RequestMapping("")
    public List<MyFile> allFile(String filePath) {
        logger.debug("上传目录:" + parentPath);
        File parentDir;
        if (filePath == null) {
            parentDir = new File(parentPath);
            logger.debug("查询" + parentPath + "路径文件");
        } else {
            parentDir = new File(parentPath, filePath);
            logger.debug("查询" + parentPath + "/" + filePath + "路径文件");
        }
//        不存在则创建
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
        // 获取所有文件
        File[] files = parentDir.listFiles();
        if (files != null) {
            List<MyFile> returnFiles = new ArrayList<>();
            for (File f : files) {
//              数据大小单位的显示设置
                String size = FileUtils.sizeFormat(f);
                String FileType = FileUtils.getFileType(f);
                returnFiles.add(new MyFile(f.getName(), size, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(f.lastModified())), FileType));
            }
            return returnFiles;
        } else {
            return null;
        }
    }

    @RequestMapping("upload")
    @ResponseBody
    public String upload(MultipartFile file, Boolean sure, String uploadPath) {
        File parentDir;
        if (uploadPath == null || "".equals(uploadPath)) {
            parentDir = new File(parentPath);
        } else {
            parentDir = new File(parentPath, uploadPath);
        }
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        File targetFile = new File(parentDir, Objects.requireNonNull(file.getOriginalFilename()));
        if (targetFile.exists()) {
            if (!sure) {
                return "exist";
            }
            try {
                file.transferTo(targetFile);
                return "success";
            } catch (IOException e) {
                e.printStackTrace();
                return "fail";
            }
        } else {
            try {
                file.transferTo(targetFile);
                return "success";
            } catch (IOException e) {
                e.printStackTrace();
                return "fail";
            }
        }
    }

    @RequestMapping("/download")
    public void download(String filename, boolean onlineOpen, HttpServletResponse response) throws IOException {
        File file = new File(parentPath, filename);
        // 在线预览
        if (!onlineOpen) {
            // 防止中文乱码
            filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setHeader("content-disposition", "attachment;fileName=" + filename);
        }
        // 如果不是文件夹则下载
        if (!file.isDirectory()) {
            InputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
            IOUtils.closeQuietly(inputStream);
        }
//        } else {
//            if (onlineOpen) {
//                response.sendRedirect("/files/?filePath="+filename);
//            }
//        }


    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String filename) {
        File file = new File(parentPath, filename);
        file.delete();
        return "success";
    }

    @RequestMapping("/mkdir")
    @ResponseBody
    public String makeDir(String dirName, String currentPath) {
        File file = new File(parentPath+"/" + currentPath, dirName);
        boolean isSuccess = file.mkdirs();
        if (isSuccess) {
            return "success";
        } else {
            return "failed";
        }
    }
}
